
import Vue from "vue";
import Vuex from 'vuex'
const actions={

}
const mutations={
    addCar(state,goodsInfo){
        var flag=false
        state.car.some((item)=>{
            if(item.skuId===goodsInfo.skuId){
                item.buyAmount+=parseInt(goodsInfo.buyAmount)
                flag=true
                return true
            }
        })
        if(!flag){
            state.car.push(goodsInfo)
            sortByKey(state.car,'id')
        }
        setItem('car',state.car)
    },
    updateGoodsInfo(state,goodsInfo){
        state.car.some((item)=>{
            if(item.skuId===goodsInfo.id){
                item.buyAmount=parseInt(goodsInfo.buyAmount)
                return true
            }
        })
        setItem('car',state.car)
    },
    updateGoodsSelected(state,info){
        state.car.some((item)=>{
            if(item.skuId===info.id){
                item.selected=info.selected
            }
        })
        setItem('car',state.car)
    },
    clearCar(state){
        console.log('state',state)
        state.car=[]
        removeItem('car')
    },
    removeCar(state,id){
        state.car.some((item,i)=>{
            if(item.skuId===id){
                state.car.splice(i,1)
                return true
            }
        })
        setItem('car',state.car)
    },
    addOrder(state,buyGoodsList){
        state.buyOrderList=buyGoodsList
    }
}
function setItem(name,item){
    localStorage.setItem(name,JSON.stringify(item))
}
function getItem(name){
    return JSON.parse(localStorage.getItem(name)||'[]')
}
function removeItem(name){
    return localStorage.removeItem(name)
}
function sortByKey(array,key){
    return array.sort(function(a,b){
        var x=a[key]
        var y=b[key]
        return x<y ? -1 : x>y ? 1:0
    })
}
const state={
    car:getItem('car'),
    buyOrderList:[],
}
const getters={
    getGoodsCount(state){
        var goods={}
        state.car.forEach((item)=>{
            goods[item.skuId]=item.buyAmount
        })
        return goods
    },
    getGoodsSelected(state){
        var goods={}
        state.car.forEach((item)=>{
            goods[item.skuId]=item.selected
        })
        return goods
    },
    getCount(state){
        return state.car.length||''
    },
    getSelectedCount(state){
        var count=0
        state.car.forEach((item)=>{
            if(item.selected){
                count+=1
            }
        })
        return count
    },
    getSelectedGoods(state){
        var goods={}
        state.car.forEach((item)=>{
            if(item.selected){
                goods[item.skuId]=item
            }
        })
        return goods
    }
}
Vue.use(Vuex)
export default new Vuex.Store({
    actions,
    mutations,
    state,
    getters,
})